package service

import (
	"context"
	"encoding/json"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"go_private_im/internal/logic/biz"
	"time"

	pb "go_private_im/api/logic"
)

type LogicService struct {
	pb.UnimplementedLogicServer
	log *log.Helper
	uc *biz.LogicUsecase
}

func NewLogicService(logger log.Logger,uc *biz.LogicUsecase) *LogicService {
	return &LogicService{log: log.NewHelper(logger),uc: uc}
}
func (s *LogicService) Connect(ctx context.Context, req *pb.ConnectReq) (*pb.ConnectReply, error) {
	token := &biz.Token{}
	if err := json.Unmarshal(req.Token, token); err != nil {
		s.log.Errorf("json.Unmarshal(%s) error(%v)", req.Token, err)
		return nil, errors.New(500,"token Unmarshal error","token Unmarshal error")
	}
	connReq := &biz.ConnectReq{Token:token,Server: req.Server}
	rep,err := s.uc.Connect(ctx,connReq)
	if err != nil {
		return nil, errors.New(404,"check Room error","check Room error")
	}
	return &pb.ConnectReply{UserId: rep.UserId,Heartbeat: rep.Heartbeat,RoomId: rep.RoomId,Accepts: rep.Accepts,Key: rep.Key}, nil
}
func (s *LogicService) Disconnect(ctx context.Context, req *pb.DisconnectReq) (*pb.DisconnectReply, error) {
	DReq := &biz.DisconnectReq{
		Key: req.Key,
		UserId: req.UserId,
		Server: req.Server,
	}
	has,err := s.uc.Disconnect(ctx,DReq)
	if err != nil {
		return &pb.DisconnectReply{}, err
	}
	return &pb.DisconnectReply{Has: has}, nil
}
func (s *LogicService) Heartbeat(ctx context.Context, req *pb.HeartbeatReq) (*pb.HeartbeatReply, error) {
	DReq := &biz.DisconnectReq{
		Key: req.Key,
		UserId: req.UserId,
		Server: req.Server,
	}
	err := s.uc.Heartbeat(ctx,DReq)
	if err != nil {
		return &pb.HeartbeatReply{}, errors.New(500,err.Error(),err.Error())
	}
	return &pb.HeartbeatReply{}, nil

}
func (s *LogicService) RenewOnline(ctx context.Context, req *pb.OnlineReq) (*pb.OnlineReply, error) {
	online := &biz.Online{
		Server: req.Server,
		RoomCount: req.RoomCount,
		Updated: time.Now().Unix(),
	}
	all,err := s.uc.RenewOnline(ctx,online)
	if err != nil {
		return &pb.OnlineReply{} ,errors.New(500,err.Error(),err.Error())
	}
	return &pb.OnlineReply{AllRoomCount: all}, nil
}
func (s *LogicService) Receive(ctx context.Context, req *pb.ReceiveReq) (*pb.ReceiveReply, error) {
	s.log.Infof("receive user_id :%d message:%+v", req.UserId, req.Proto)
	return &pb.ReceiveReply{}, nil
}
func (s *LogicService) Nodes(ctx context.Context, req *pb.NodesReq) (*pb.NodesReply, error) {
	return &pb.NodesReply{}, nil
}
